package org.atguigu.gmall.realtime.util;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Project:gmallRealTime
 * Package:org.atguigu.gmall.realtime.util
 * Author: ZengHaiFeng
 * CreateTime:2023/4/22 18:46:18
 * Description: Todo
 * Version：1.0
 */
public class AtguiguUtil {
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static String tsToDate(Long ts) {
        Date date = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dtf.format(localDateTime);
    }

    /**
     * @description:
     * @author: zenghaifeng
     * @date: 2023/4/27 17:03
     * @param s
     * @return Set<String>
     **/
    public static Set<String> ikSplit(String s) {
        // define a hash set that storage final result
        HashSet<String> set = new HashSet<>();
        /*
            new an IKSEGMENTER.
            StringReader is a stream over memory, convert a string to a stream
            true, enable smart mode.
            false max mode lists all the possible.
         */
        IKSegmenter ikSegmenter = new IKSegmenter(new StringReader(s), true);
        /*
            The next() method of ikSegmenter will get one of the values.
            Before the first called, the pointer is point to the null,
            when called time the pointer moves the first value.
            Hence, every called will return the next value since end return null.
         */
        Lexeme next;
        try {
            next = ikSegmenter.next();
            while (next != null){
                // get value from lexeme object
                String value = next.getLexemeText();
                set.add(value);
                // get next
                next = ikSegmenter.next();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return set;
    }

    public static String tsToDateTime(long ts) {
        Date date = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dateTimeFormatter.format(localDateTime);
    }

    public static Long DateToTs(String dateTime) {
        LocalDateTime localDateTime;
        localDateTime = LocalDateTime.parse(dateTime, dateTimeFormatter);
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }
}
